﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using HZ.Supervise.Model;

namespace HZ.Supervise.Web.Secondphase.ReportHospital
{
    public partial class AddSubsidyDetail : BasePage
    {
        HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
        int totalrecord = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind();
            }
        }
        void Bind()
        {
            if (Request["id"] != null)
            {
                IList<HZ.Supervise.Model.Subsidy> SubsidyList = new List<HZ.Supervise.Model.Subsidy>();
                HZ.Data.QueryModel qm = new HZ.Data.QueryModel();
                qm["SubsidyID"] = Request["id"].ToString();
                qm["SortFields"] = "  SubsidyID ASC";
                AspNetPager1.RecordCount = totalrecord;
                SubsidyList = iPrescription.GetSubsidyList(qm, 0, 0, out totalrecord);
                if (SubsidyList != null && SubsidyList.Count > 0)
                {
                    labHospitalname.Text = SubsidyList[0].SHospitalName;
                    labSubsidyID.Text = SubsidyList[0].SubsidyID;
                    int totalrecord1 = 0;
                    string strwhere = " and PSbsidyAmount<PSubsidiesAmount and POrderStatus =1 ";
                    strwhere += "and pHospitalID= '" + SubsidyList[0].SHospitalID+"'";
                    if (!txtStratTime.Text.Trim().Equals("")) //开始时间
                    {
                        strwhere += " and PSubmitTime >='" + (new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                    }
                    if (!txtEndTime.Text.Trim().Equals("")) //结束时间
                    {
                        strwhere += " and PSubmitTime <='" + (new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                    }
                    DataTable dt = iPrescription.GetHospitaleNoPrescrip(strwhere, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out totalrecord);
                    AspNetPager1.RecordCount = totalrecord1;
                    this.gvwDetail.DataSource = dt;
                    this.gvwDetail.DataBind();
                }
            }
        }

        protected void btnFinish_Click(object sender, EventArgs e)
        {
            if (gvwDetail.Rows.Count > 0)
            {
                IList<HZ.Supervise.Model.SubsidyDetail> SubsidyDetailList = new List<HZ.Supervise.Model.SubsidyDetail>();
                IList<Prescription> prescriptionList = new List<Prescription>();
                StringBuilder sb = new StringBuilder();
                foreach (GridViewRow item in gvwDetail.Rows)
                {
                    if (item.RowType == DataControlRowType.DataRow)
                    {
                        CheckBox check = (CheckBox)item.Cells[0].FindControl("CheckBox1");
                        if (check.Checked)
                        {
                            HZ.Supervise.Model.SubsidyDetail newSubsidyDetail = new HZ.Supervise.Model.SubsidyDetail();

                            string strPrice = ((TextBox)item.FindControl("txtCount")).Text.Trim();//补助
                            string strbz = ((TextBox)item.FindControl("txtBZ")).Text.Trim();//备注
                            if (string.IsNullOrEmpty(strPrice))
                            {
                                Response.Write("<script>alert('请填写补助金额！')</script>");
                                return;
                            }
                            string strPSbsidyAmount = item.Cells[6].Text.Trim();
                            string strPSubsidiesAmount = item.Cells[5].Text.Trim();
                            string strhospitalid = item.Cells[3].Text.Trim();
                            string SsumAmount = item.Cells[4].Text.Trim();
                            string SubsidyID = Request["id"].ToString();
                            //补助金额
                            decimal price = Convert.ToDecimal(strPrice);
                            //应补助金额
                            decimal PSubsidiesAmount = Convert.ToDecimal(strPSubsidiesAmount);
                            //已补助金额
                            decimal PSbsidyAmount = Convert.ToDecimal(strPSbsidyAmount);
                            //判断补助金额的准确性
                            if ((price + PSbsidyAmount) > PSubsidiesAmount)
                            {
                                Response.Write("<script>alert('补助金额不能大于应补助金额！')</script>");
                                return;
                            }
                            string strstartime = "", strendtime = "";
                            string strwhere = "  and PSbsidyAmount<PSubsidiesAmount and POrderStatus=1 ";
                            string userid = CurrentAccount.GetUser().UserID;
                            if (!txtStratTime.Text.Trim().Equals("")) //开始时间
                            {
                                strwhere += " and PSubmitTime >='" + (new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                                if (!string.IsNullOrEmpty(txtStratTime.Text.Trim()))
                                {
                                    strstartime = txtStratTime.Text.Trim();
                                }

                            }
                            if (!txtEndTime.Text.Trim().Equals("")) //结束时间
                            {
                                strwhere += " and PSubmitTime <='" + (new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime).Value.ToString() + "'";
                                strendtime = txtEndTime.Text.Trim();
                            }
                            else
                            {
                                strendtime = System.DateTime.Now.ToString();//无结束时间就是当前时间
                            }

                            newSubsidyDetail.SubsidyDetailId = Guid.NewGuid().ToString();
                            newSubsidyDetail.SubsidyID = labSubsidyID.Text;
                            newSubsidyDetail.PrescriptionId = item.Cells[12].Text.Trim();
                            if (!string.IsNullOrEmpty(strbz))
                            {
                                newSubsidyDetail.PRemark = strbz;
                            }
                            else
                            {
                                newSubsidyDetail.PRemark = "";
                            }
                            newSubsidyDetail.PSbsidyAmount = price;
                            SubsidyDetailList.Add(newSubsidyDetail);
                            //查询出该医院处方单的应补助金额，已补助金额，处方单Id
                            IList<HZ.Supervise.Model.Subsidy> SubsidyList = new List<HZ.Supervise.Model.Subsidy>();
                            HZ.Data.QueryModel qm = new HZ.Data.QueryModel();
                            qm["SubsidyID"] = Request["id"].ToString();
                            qm["SortFields"] = "  SubsidyID ASC";
                            AspNetPager1.RecordCount = totalrecord;
                            SubsidyList = iPrescription.GetSubsidyList(qm, 0, 0, out totalrecord);
                             strwhere += " and PSbsidyAmount<PSubsidiesAmount and POrderStatus =1 ";
                            strwhere += "and pHospitalID= '" + SubsidyList[0].SHospitalID + "'";
                            DataTable dt2 = iPrescription.GetHospitaleTB_Prescription(strwhere);
                            if (dt2.Rows.Count > 0)
                            {
                                if (string.IsNullOrEmpty(strstartime))
                                {
                                    strstartime = dt2.Rows[0]["PSubmitTime"].ToString();
                                }
                                for (int i = 0; i < dt2.Rows.Count; i++)
                                {
                                    Prescription prescription = new Prescription();

                                    //处方单中应补助金额
                                    decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[i]["PSubsidiesAmount"].ToString());
                                    //处方单中的已补助金额
                                    decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[i]["PSbsidyAmount"].ToString());
                                    //判断处方单中是否有已补助金额
                                    if (prePSbsidyAmount > 0)
                                    {
                                        //算出未补贴金额
                                        decimal UnPSbsidyAmount = prePSubsidiesAmount - prePSbsidyAmount;
                                        //若未补助金额大于补贴金额
                                        if (UnPSbsidyAmount > price)
                                        {

                                            prescription.POrderStatus = 2;
                                            //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                            prescription.PSbsidyAmount = prePSbsidyAmount + (UnPSbsidyAmount - price);
                                            prescription.PSubmitTime = DateTime.Now;
                                            prescription.PSubsidyUserid = userid;
                                            prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                            prescriptionList.Add(prescription);
                                            //sb.Append("update TB_Prescription set POrderStatus='2',PSbsidyAmount=PSbsidyAmount+" + (UnPSbsidyAmount - price) + ", PSubsidyTime=GETDATE(),PSubsidyUserid='" + userid + "' where PHospitalId='" + strhospitalid + "' " + strwhere + " and PrescriptionId ='" + dt2.Rows[i]["PrescriptionId"] + "'");
                                            //sb.Append("insert dbo.TB_SubsidyDetail([SubsidyDetailId],[SubsidyID] ,[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],[PSbsidyAmount],[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],PrescriptionId,PSubsidiesAmount) select '" + Guid.NewGuid().ToString() + "','" + SubsidyID + "',[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],PSbsidyAmount+" + (UnPSbsidyAmount - price) + ",[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],'" + dt2.Rows[i]["PrescriptionId"].ToString() + "',PSubsidiesAmount  from TB_Prescription where 1=1 and PrescriptionID ='" + dt2.Rows[i]["PrescriptionId"].ToString() + "'");
                                            price = 0;
                                            break;
                                        }
                                        else
                                        {
                                            prescription.POrderStatus = 2;
                                            //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                            prescription.PSbsidyAmount = prePSubsidiesAmount;
                                            prescription.PSubmitTime = DateTime.Now;
                                            prescription.PSubsidyUserid = userid;
                                            prescription.PrescriptionId = dt2.Rows[i]["PrescriptionId"].ToString();
                                            prescriptionList.Add(prescription);
                                            //更新处方单表并把处方单中
                                            //sb.Append("update TB_Prescription set POrderStatus='2',PSbsidyAmount=" + prePSubsidiesAmount + ",PSubsidyTime=GETDATE(),PSubsidyUserid='" + userid + "' where PHospitalId='" + strhospitalid + "' " + strwhere + " and PrescriptionId ='" + dt2.Rows[i]["PrescriptionId"] + "'");
                                            //sb.Append("insert dbo.TB_SubsidyDetail([SubsidyDetailId],[SubsidyID] ,[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],[PSbsidyAmount],[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],PrescriptionId,PSubsidiesAmount) select '" + Guid.NewGuid().ToString() + "','" + SubsidyID + "',[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],'" + prePSubsidiesAmount + "',[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],'" + dt2.Rows[i]["PrescriptionId"].ToString() + "',PSubsidiesAmount  from TB_Prescription where 1=1 and PrescriptionID ='" + dt2.Rows[i]["PrescriptionId"].ToString() + "'");
                                            price = price - UnPSbsidyAmount;
                                        }

                                    }

                                }
                                if (price > 0)
                                {
                                    for (int j = 0; j < dt2.Rows.Count; j++)
                                    {
                                        Prescription prescription = new Prescription();
                                        //处方单中应补助金额
                                        decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[j]["PSubsidiesAmount"].ToString());
                                        //处方单中的已补助金额
                                        decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[j]["PSbsidyAmount"].ToString());
                                        //添加以补助金额为0的数据
                                        if (prePSbsidyAmount <= 0)
                                        {

                                            //处方单应补助金额大于补助金额
                                            if (prePSubsidiesAmount > price)
                                            {
                                                prescription.POrderStatus = 2;
                                                //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                                prescription.PSbsidyAmount = prePSbsidyAmount + price;
                                                prescription.PSubmitTime = DateTime.Now;
                                                prescription.PSubsidyUserid = userid;
                                                prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                                prescriptionList.Add(prescription);
                                                string gu = Guid.NewGuid().ToString();
                                                //更新处方单表
                                                //sb.Append("update TB_Prescription set POrderStatus='2',PSbsidyAmount=PSbsidyAmount+" + price + ",PSubsidyTime=GETDATE(),PSubsidyUserid='" + userid + "' where PHospitalId='" + strhospitalid + "' " + strwhere + " and PrescriptionId ='" + dt2.Rows[j]["PrescriptionId"] + "'");
                                                //sb.Append("insert dbo.TB_SubsidyDetail([SubsidyDetailId],[SubsidyID] ,[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],[PSbsidyAmount],[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],PrescriptionId,PSubsidiesAmount) select '" + Guid.NewGuid().ToString() + "','" + SubsidyID + "',[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],'" + price + "',[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],'" + dt2.Rows[j]["PrescriptionId"].ToString() + "',PSubsidiesAmount  from TB_Prescription where 1=1 and PrescriptionID ='" + dt2.Rows[j]["PrescriptionId"].ToString() + "'");
                                                price = 0;
                                                break;
                                            }
                                            else
                                            {
                                                prescription.POrderStatus = 2;
                                                //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                                prescription.PSbsidyAmount =prePSubsidiesAmount;
                                                prescription.PSubmitTime = DateTime.Now;
                                                prescription.PSubsidyUserid = userid;
                                                prescription.PrescriptionId = dt2.Rows[j]["PrescriptionId"].ToString();
                                                prescriptionList.Add(prescription);
                                                string gu = Guid.NewGuid().ToString();
                                                ////处方单金额小于补助金额
                                                //sb.Append("update TB_Prescription set POrderStatus='2',PSbsidyAmount=PSbsidyAmount+" + prePSubsidiesAmount + ",PSubsidyTime=GETDATE(),PSubsidyUserid='" + userid + "' where PHospitalId='" + strhospitalid + "' " + strwhere + " and PrescriptionId ='" + dt2.Rows[j]["PrescriptionId"] + "'");
                                                price = price - prePSubsidiesAmount;
                                            }
                                            ////添加到结算单明细表中
                                            //sb.Append("insert dbo.TB_SubsidyDetail([SubsidyDetailId],[SubsidyID] ,[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],[PSbsidyAmount],[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],PrescriptionId,PSubsidiesAmount) select '" + Guid.NewGuid().ToString() + "','" + SubsidyID + "',[PAreaId],[PAreaname],[PHospitalId],[PHospitalName],[PatientName],[PHisPId] ,[PdoctorName],[PtotalAmount],[PEssentialDrugsAmount],'" + prePSubsidiesAmount + "',[PAge],[PSex],[Paddtime] ,[PisSubsidy],[PSubsidyTime],[PSubsidyUserid],[PsympToms] ,[POrderStatus] ,[PRemark],[PrescriptionName],'" + dt2.Rows[j]["PrescriptionId"].ToString() + "',PSubsidiesAmount  from TB_Prescription where 1=1 and PrescriptionID ='" + dt2.Rows[j]["PrescriptionId"].ToString() + "'");
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
                if (SubsidyDetailList.Count > 0)
                {
                    Subsidy subsidy = new Subsidy();
                    subsidy.SubsidyID = Request["id"].ToString();
                    int nresult = iPrescription.UpdateAll(subsidy,prescriptionList,1);
                     int res =0;
                    if (nresult > 0)
                    {
                       res= iPrescription.AddSubsidyDetailToSubsidy(SubsidyDetailList);
                    }
                    if (res > 0)
                    {
                        Response.Write("<script>alert('更新成功！')</script>");
                        Bind();
                    }
                    else
                    {
                        Response.Write("<script>alert('更新失败！')</script>");
                    }
                }
                else
                {
                    Response.Write("<script>alert('没有要更改的数据！')</script>");
                }
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex=1;
            Bind();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            Bind();
        }
    }
}
